import { getCurrentTimeParam } from "./globalTimeFilter.js";
import {API_CONFIG} from "./config.js";

document.addEventListener("DOMContentLoaded", function () {
  // 获取满意度统计容器
  const leftBottomElement = document.getElementById("left-bottom");
  if (!leftBottomElement) return;

  // 创建新的满意度统计结构
  leftBottomElement.innerHTML = `
        <div class="satisfaction-container">
                <div id="satisfaction-pie" style="height:100%; width: 100%;"></div>
        </div>
    `;

  // 添加样式
  const style = document.createElement("style");
  style.innerHTML = `
        .satisfaction-container {
            display: flex;
            height: 100%;
            width: 100%;
            border-radius: 8px;
            padding: 10px;
            border: 1px solid rgba(36, 187, 236, 0.2);
        }
    `;
  document.head.appendChild(style);

  // 初始化饼图
  const satisfactionChart = echarts.init(
    document.getElementById("satisfaction-pie")
  );

  // 实时更新数据和动画效果
  function updateSatisfactionChart() {
    let timeParam = getCurrentTimeParam();
    const id = "gfntgsdfwca044c1b0dbb1dessdgsegc"; // 图片中的固定ID
    const time = timeParam; // 图片中的time值
    const type = "2"; // 图片中的type值

    // 准备请求参数
    const params = new URLSearchParams();
    params.append("id", id);
    params.append("time", time);
    params.append("type", type);
    // 图片中whereCondition未勾选，不添加

    // 构建完整的URL
    const url = `${API_CONFIG.BASE_URL}/api/metrics/${id}/single-metrics-value?${params.toString()}`;

    axios
      .get(url)
      .then((response) => {
        if (response.data && response.data.code === "00000") {
          const result = response.data.data;

          // 处理数据，提取满意度和数量
          const dataList = [];
          const legendData = [];

          // 图片中显示的响应数据结构示例：
          // {
          //   "id": "72",
          //   "satisfaction_type": "非常满意",
          //   "satisfaction_count": "8",
          //   "year": "2024"
          // }
          result.forEach((item) => {
            const satisfactionType = item.satisfaction_type;
            const count = parseInt(item.satisfaction_count);

            // 只处理有满意度的数据
            if (satisfactionType) {
              dataList.push({
                name: satisfactionType,
                value: count,
              });
              legendData.push(satisfactionType);
            }
          });

          const option = {
            tooltip: {
              trigger: "item",
              formatter: "{b}: {c} ({d}%)", // {b} 类别, {c} 数量, {d} 百分比
              backgroundColor: "rgba(6, 33, 68, 0.9)",
              borderColor: "#24bbec",
              textStyle: {
                color: "#fff",
              },
            },
            legend: {
              orient: "horizontal",
              bottom: 10,
              left: "center",
              textStyle: {
                color: "#a2d3e8",
                fontSize: 14,
              },
              data: legendData,
            },
            series: [
              {
                name: "满意度",
                type: "pie",
                radius: ["50%", "80%"],
                center: ["50%", "50%"],
                avoidLabelOverlap: false,
                itemStyle: {
                  borderColor: "#031c3d",
                  borderWidth: 2,
                },
                label: {
                  show: false,
                  position: "center",
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: "14",
                    fontWeight: "bold",
                    color: "#fff",
                  },
                },
                labelLine: {
                  show: false,
                },
                data: dataList.map((item) => ({
                  ...item,
                  itemStyle: {
                    color:
                      item.name === "非常满意"
                        ? "#24d39a"
                        : item.name === "满意"
                        ? "#24bbec"
                        : "#ffc640",
                  },
                })),
                animationType: "scale",
                animationEasing: "elasticOut",
                animationDuration: 1000,
              },
            ],
          };
          satisfactionChart.setOption(option);

          // 更新更新时间
          updateUpdateTime();
        } else {
          console.error(
            "获取满意度数据失败:",
            response.data ? response.data.msg : "未知错误"
          );
        }
      })
      .catch((error) => {
        console.error("获取满意度数据失败:", error);
      });
  }

  document.addEventListener("timePeriodChanged", function () {
    updateSatisfactionChart();
  });

  // 更新更新时间
  function updateUpdateTime() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, "0");
    const minutes = now.getMinutes().toString().padStart(2, "0");
    const seconds = now.getSeconds().toString().padStart(2, "0");

    const updateTimeElement = document.getElementById(
      "satisfaction-update-time"
    );
    if (updateTimeElement) {
      updateTimeElement.textContent = `${hours}:${minutes}:${seconds}`;
    }
  }

  // 初始设置
  updateSatisfactionChart();

  // 每5秒更新一次数据
  setInterval(updateSatisfactionChart, 5000000);

  // 窗口大小变化时调整图表尺寸
  window.addEventListener("resize", function () {
    satisfactionChart.resize();
  });
});
